import { useEffect, useRef, useState } from 'react';
import GdMap from '@/utils/GdMap';
import Search from './Search';
import { SearchIcon } from '@/components/icons';
import { ClickInfo } from '@/utils/GdMap';

type Props = {
   onPosition?: (ClickInfo) => void;
   center?: [number, number];
};
const MapSelector = ({ onPosition, center }: Props) => {
   const map = useRef<GdMap>(); // 地图js
   const [isSearch, setIsSearch] = useState(false); // 是否显示搜索界面

   const [des, setDes] = useState(''); // 点位描述信息

   // 更改点位
   const handlePosition = (info) => {
      setDes(info.address);
      onPosition(info); // 返回经纬度和详细地址
   };

   const handleCloseSearch = () => {
      setIsSearch(false);
   };

   useEffect(() => {
      // 初始化地图
      map.current = new GdMap('container', {
         init: {
            center,
         },
         extends: {
            showCenterMarker: true,
            changeCenterByClick: true,
            onInitPosition: handlePosition,
            onClickPosition: handlePosition,
         },
      });
      map.current.init();

      () => {
         map.current.destroy();
      };
   }, []);

   return (
      <>
         <div id="container" className="w-full h-full"></div>
         <div className="absolute bottom-6 w-full">
            <div
               className="rounded-md shadow-lg  bg-white p-2 w-11/12 mx-auto flex items-center space-x-1"
               onClick={() => {
                  setIsSearch(true);
               }}
            >
               <div className="grow">{des}</div>
               <SearchIcon />
            </div>
         </div>

         {isSearch && (
            <Search
               map={map.current}
               initValue={des}
               key={des}
               onClose={handleCloseSearch}
               onSelect={(info) => {
                  const { lng, lat } = info.location;
                  map.current.center.setMakerAndShift(lng, lat);
                  const address = `${info.address}${info.name}`;
                  setDes(address);
                  onPosition({
                     lng,
                     lat,
                     address,
                  });
                  handleCloseSearch();
               }}
            />
         )}
      </>
   );
};

export default MapSelector;
